<template>
  <el-dialog
    v-model="dialogVisible"
    title="移动文件"
    :draggable="true"
    :destroy-on-close="true"
    :fullscreen="isMobile"
  >
    <el-tree :load="loadNode" lazy accordion @node-click="handleNodeClick" />
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, computed } from "vue";
import { getFoldersApi, moveFileApi, moveFilesApi, copyFileApi, saveShareApi } from "../api";
import { ElMessage } from "element-plus";
import { useWindowSize } from "@vueuse/core";
const { width } = useWindowSize();
const isMobile = computed(() => width.value < 768);

const emits = defineEmits(["finish"]);
const dialogVisible = ref(false);

let fileId = null;
let folderId;
let mode = null;
let psw = null;

const open = (id, m, p) => {
  mode = m;
  psw = p;
  fileId = id;
  dialogVisible.value = true;
};
const close = () => {
  dialogVisible.value = false;
};

const handleNodeClick = (data) => {
  folderId = data.id;
};

const loadNode = async (node, resolve) => {
  try {
    if (node.level === 0) {
      resolve([{ id: null, label: "我的空间" }]);
      return;
    }
    const data = await getFoldersApi(node.data.id);
    resolve(
      data.data.map((item) => ({
        id: item.id,
        label: item.filename,
        isLeaf: !item.isFolder,
      }))
    );
  } catch (error) {
    console.error("加载节点失败:", error);
    reject();
  }
};

const onConfirm = async () => {
  if (folderId === undefined) {
    ElMessage.warning("请选择文件夹");
    return;
  }
  try {
    if(mode === 'copy'){
      await copyFileApi(fileId, folderId);
      return;
    }
    if(mode === 'share'){
      await saveShareApi(fileId, psw, folderId);
      return; 
    }
    if (Array.isArray(fileId)) {
      console.log(fileId, folderId);
      await moveFilesApi(fileId, folderId);
    } else {
      await moveFileApi(fileId, folderId);
    }
  } catch (error) {
    console.error("移动文件失败:", error);
    return;
  }finally{
    emits("finish");
    close();
  }
};
defineExpose({
  open,
  close,
});
</script>
